/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.inspur.edp.web.formmetadata.metadataanalysis;

import com.inspur.edp.lcm.metadata.api.entity.GspMetadata;
import com.inspur.edp.web.common.JITEngineConstants;
import com.inspur.edp.web.common.environment.ExecuteEnvironment;
import com.inspur.edp.web.common.utility.StringUtility;
import com.inspur.edp.web.formmetadata.metadata.formdom.FormDOM;
import com.inspur.edp.web.formmetadata.metadatamanager.MetadataManagerParameter;
import com.inspur.edp.web.formmetadata.metadatamanager.StateMachineMetadataManager;
import lombok.Getter;

import java.util.HashMap;
import java.util.function.Function;

/**
 * 状态机的解析
 */
public class StateMachineAnalysis extends AbstractMetadataAnalysis {

    public StateMachineAnalysis(ExecuteEnvironment executeEnvironment, boolean isUpgradeTool) {
        super(executeEnvironment, isUpgradeTool);
    }

    public void resolveStateMachine(FormDOM json, String metaDataFileName, String targetStoragePath,
                                    String relativePath,
                                    Function<ResolveStateMachineParameter, GspMetadata> getMetadataSupplier) {
        // Get StateMachine Metadata, and Save StateMachine
        if (json.getModule() != null && json.getModule().getStateMachines() != null &&
                json.getModule().getStateMachines().size() > 0) {
            StateMachineMetadataManager smManager = new StateMachineMetadataManager(this.executeEnvironment, this.isUpgradeTool, relativePath);
            StringBuilder stateMachines = new StringBuilder();
            stateMachines.append("{");
            int index = 0;
            for (HashMap<String, Object> o : json.getModule().getStateMachines()) {
                if (index > 0) {
                    stateMachines.append(",");
                }
                String uri = o.get("uri").toString();
                MetadataManagerParameter metadataManagerParameter = MetadataManagerParameter.init(uri,
                        StringUtility.getOrDefaultEmpty(o.get("code")),
                        StringUtility.getOrDefaultEmpty(o.get("name")),
                        StringUtility.getOrDefaultEmpty(o.get("nameSpace")));
                ResolveStateMachineParameter resolveStateMachineParameter = ResolveStateMachineParameter.init(metadataManagerParameter, smManager);
                GspMetadata obj = getMetadataSupplier.apply(resolveStateMachineParameter);
                String sm_json = smManager.serialize(obj.getContent());
                String idStr = o.get("id").toString();
                stateMachines.append("\"").append(idStr).append("\":");
                stateMachines.append(sm_json);
                index += 1;
            }
            stateMachines.append("}");

            // Save StateMachine
            smManager.saveMetadataFile(targetStoragePath, String.format("%1$s%2$s", metaDataFileName.toLowerCase(), JITEngineConstants.StateMachineJsonFile), stateMachines.toString());
        }
    }

    /**
     * 解析状态机元数据
     * 使用默认的StateMachineManager进行元数据读取
     */
    public void resolveStateMachine(FormDOM json, String metaDataFileName, String targetStoragePath,
                                    String relativePath) {
        resolveStateMachine(json, metaDataFileName, targetStoragePath, relativePath,
                (resolveStateMachineParameter) -> resolveStateMachineParameter.smManager.getStateMachine(resolveStateMachineParameter.metadataManagerParameter));
    }

    @Getter
    public static class ResolveStateMachineParameter {
        private MetadataManagerParameter metadataManagerParameter;
        private StateMachineMetadataManager smManager;

        private ResolveStateMachineParameter() {
        }

        public static ResolveStateMachineParameter init(MetadataManagerParameter metadataManagerParameter, StateMachineMetadataManager smManager) {
            ResolveStateMachineParameter resolveStateMachineParameter = new ResolveStateMachineParameter();
            resolveStateMachineParameter.metadataManagerParameter = metadataManagerParameter;
            resolveStateMachineParameter.smManager = smManager;
            return resolveStateMachineParameter;
        }
    }
}
